package com.vanysoft.framework.aop;

import com.alibaba.druid.util.StringUtils;
import com.vanysoft.framework.validation.VanySoftValidationErr;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Aspect
@Component
public class VanysoftValidationAspect {

    @Pointcut("@annotation(com.vanysoft.framework.aop.VanySoftValidation)")
    public void annotationPointCut() {
    }

    @Before("annotationPointCut()")
    public void before(JoinPoint joinPoint) throws VanySoftValidationException {
        BindingResult result = null;
        for (Object obj : joinPoint.getArgs()) {
            if (obj instanceof BindingResult) {
                result = (BindingResult) obj;
            }
        }
        if (result != null && result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            for (FieldError error : result.getFieldErrors()) {
                String message = StringUtils.isEmpty(map.get(error.getField())) ? "" : map.get(error.getField());
                map.put(error.getField(), message + "," + error.getDefaultMessage());
            }
            List<VanySoftValidationErr> errList = new ArrayList<>();
            for (Entry<String, String> entry : map.entrySet()) {
                VanySoftValidationErr err = new VanySoftValidationErr();
                err.setField(entry.getKey());
                err.setMessage(entry.getValue().substring(1).split(","));
                errList.add(err);
            }
            throw new VanySoftValidationException("validationErr", errList);
        }
    }
}
